package lock

import java.util.concurrent.locks.ReentrantReadWriteLock

/**
 * 读写锁的简单示例
 */
class Task {
    private val lock = ReentrantReadWriteLock()

    //读可以共享
    fun read() {
        try {
            lock.readLock().lock()
            println(Thread.currentThread().name + " read start")
            Thread.sleep(1000L)
            println(Thread.currentThread().name + " read end")
        } catch (e: Exception) {

        } finally {
            lock.readLock().unlock()
        }
    }

    //读写、写读、写写互斥
    fun write() {
        try {
            lock.writeLock().lock()
            println(Thread.currentThread().name + " write start")
            Thread.sleep(1000L)
            println(Thread.currentThread().name + " write end")
        } catch (e: Exception) {

        } finally {
            lock.writeLock().unlock()
        }
    }
}

fun main() {
    val task = Task()

    val thread1 = Thread {
        task.read()
    }
    thread1.name = "thread1"

    val thread2 = Thread {
        task.read()
    }
    thread2.name = "thread2"

    thread1.start()
    thread2.start()

    Thread.sleep(3000L)

    val thread3 = Thread {
        task.write()
    }
    thread3.name = "thread3"

    val thread4 = Thread {
        task.read()
    }
    thread4.name = "thread4"

    thread3.start()
    thread4.start()

    Thread.sleep(3000L)

    val thread5 = Thread {
        task.read()
    }
    thread5.name = "thread5"

    val thread6 = Thread {
        task.write()
    }
    thread6.name = "thread6"

    thread5.start()
    thread6.start()

    Thread.sleep(3000L)

    val thread7 = Thread {
        task.write()
    }
    thread7.name = "thread7"

    val thread8 = Thread {
        task.write()
    }
    thread8.name = "thread8"

    thread7.start()
    thread8.start()

    Thread.sleep(3000L)
}